package com.chenshu.mycnblog.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;

/**
 * Created with IntelliJ IDEA
 * Description：统一数据返回封装
 * User：chenshu
 * Date：2024-01-02
 * Time：11:44
 */
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        //防止响应嵌套，如果返回的数据为HashMap类，就不继续走后面的代码
        return !returnType.getParameterType().equals(HashMap.class);
    }

    @SneakyThrows //消除非受检异常的冗余代码
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        //在body是String的时候，Spring选择使用 StringHttpMessageConverter把HashMap转成String
        //防止异常发生，向下面这样处理
        if (body instanceof String) {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.writeValueAsString(MyResponse.success(body));
        }

        return MyResponse.success(body);
    }
}


